package jude.java.money.sly;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jude.java.util.WebUtils;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

//http://www.google.com/search?hl=en&newwindow=1&q=ugg+outlet&btnG=Search&aq=f&aqi=&aql=&oq=&gs_rfai=
//<a href="/search?q=ugg+outlet&amp;hl=en&amp;newwindow=1&amp;biw=1400&amp;bih=925&amp;ei=x5TVTJmkC8G3cMbP3K8L&amp;start=10&amp;sa=N" class=fl>
//http://www.google.com/search?q=ugg+outlet&hl=en&newwindow=1&ei=L5bVTKqxCIW3cJ7AqdQL&start=60&sa=N
public class GoogleUrl {

	private static final String LANG = Sly.LANG;
	private static final String GOOGLE = Sly.GOOGLE;
	
	private String keyword;
	private String ei;
	
	public GoogleUrl(String keyword) {
		this.keyword = parseKeyword(keyword);
	}
	
	public String[] getUrls(int pageStart, int pageCount) {
		if (pageStart < 0 || pageCount < 1)
			return null;
		String url = "http://" + GOOGLE + "/search?hl=" + LANG + "&newwindow=1&q=" + keyword + "&num=100&btnG=Search&aq=f&aqi=&aql=&oq=&gs_rfai=";
		String[] urls = new String[pageCount];
		if (pageStart == 0) {
			urls[0] = url;
			if (pageCount == 1)
				return urls;
		} else {
			url += "&start=" + (pageStart * 10);
		}
		try {
			fetchEI(url);
		} catch (Exception e) {
		}
		if (ei == null) {
			for (int i = 0; i < pageCount; i++) {
				if (pageStart == 0 && i == 0)
					continue;
				urls[i] = url + "&start=" + ((i + pageStart) * 10);
			}
			return urls;
		}
		for (int i = 0; i < pageCount; i++) {
			if (pageStart == 0 && i == 0)
				continue;
			urls[i] = "http://" + GOOGLE + "/search?q=" + keyword + "&hl=" + LANG +"&newwindow=1&ei=" + ei + "&sa=N&start=" + ((i + pageStart) * 10);
		}
		return urls;
	}
	
	public String[] getUrls(int pageCount) {
		return getUrls(0, pageCount);
//		String url = "http://" + GOOGLE + "/search?hl=" + LANG + "&newwindow=1&q=" + keyword + "&btnG=Search&aq=f&aqi=&aql=&oq=&gs_rfai=";
//		String[] urls = new String[pageCount];
//		urls[0] = url;
//		if (pageCount <= 1)
//			return urls;
//		try {
//			fetchEI(url);
//		} catch (Exception e) {
//		}
//		if (ei == null) {
//			for (int i = 1; i < pageCount; i++) {
//				urls[i] = url + "&start=" + (i * 10);
//			}
//			return urls;
//		}
//		for (int i = 1; i < pageCount; i++) {
//			urls[i] = "http://" + GOOGLE + "/search?q=" + keyword + "&hl=" + LANG +"&newwindow=1&ei=" + ei + "&sa=N&start=" + (i * 10);
//		}
//		return urls;
	}
	
	private void fetchEI(String url) throws HttpException, IOException {
		HttpClient client = new DefaultHttpClient();
		client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
//		client.getHttpConnectionManager().closeIdleConnections(60000);
		HttpGet get = new HttpGet(url);
//		GetMethod get = new GetMethod(url);
		WebUtils.pretendRequestHeader(get);
		get.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.TRUE);
//		get.setFollowRedirects(true);
		HttpResponse response = client.execute(get);
		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode != HttpStatus.SC_OK) {
			get.abort();
//			get.releaseConnection();
			return;
		}
//		String resp = WebUtils.getResponse(get, 0, "UTF-8");
		String resp = WebUtils.getResponse(response, 0, "UTF-8");
		String regexp = "<a href=\"/search\\?q=[^\">]+ei=([^\"\\&]+)[^\"]*\" class=fl>";
		Pattern p = Pattern.compile(regexp);
		Matcher m = p.matcher(resp);
		if (m.find()) {
			this.ei = m.group(1);
			System.out.println("ei=" + ei);
		}
//		get.releaseConnection();
		get.abort();
	}
	
	private static String parseKeyword(String keyword) {
		if (StringUtils.isEmpty(keyword))
			return null;
		String[] keys = StringUtils.split(keyword);
		StringBuilder sb = new StringBuilder();
		if (keys.length == 0) {
			return "";
		} else if (keys.length == 1) {
			sb.append(keys[0]);
		} else {
			for (int i = 0; i < keys.length; i++) {
				if (i != 0)
					sb.append(' ');
				sb.append(keys[i]);
			}
		}
		try {
			return URLEncoder.encode(sb.toString(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
		}
		return sb.toString();
	}
}
